package nioTest.nio1;

import io.netty.channel.nio.AbstractNioChannel;
import org.apache.ibatis.annotations.SelectKey;
import sun.nio.ch.SelChImpl;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NioServer1 {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        ServerSocket serverSocket = serverChannel.socket();

        serverSocket.bind(new InetSocketAddress(8899));

        Selector selector = Selector.open();

        serverChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey k = iterator.next();
                iterator.remove();
                int readyOps = k.readyOps();
                if ((readyOps & SelectionKey.OP_CONNECT) != 0) {
                    int ops = k.interestOps();
                    ops &= ~SelectionKey.OP_CONNECT;
                    k.interestOps(ops);

//                    unsafe.finishConnect();
                    System.out.println("finishConnect");
                }

                if ((readyOps & SelectionKey.OP_WRITE) != 0) {
//                    ch.unsafe().forceFlush();
                    System.out.println("forceFlush");
                }

                if ((readyOps & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0 || readyOps == 0) {
//                    unsafe.read();
                    System.out.println("safdasdf");
                }
            }
        }
    }
}
